package org.aes.util;

import android.content.Context;

public class CAESEncrypt {
	
	/**
	 * 初始化加密组件
	 * @param context
	 * @return
	 */
	public static native boolean initialize(Context context);
	
	/**
	 * AES解密
	 * @param input
	 * @return
	 */
	public static byte[] DecodeAESEncrypt(byte[] input){
		byte[] output = new byte[getLength(input.length)];
		int len = DecodeAESEncrypt(input, output, input.length);
		byte[] out = new byte[len];
		for(int i = 0; i < len; i++){
			out[i] = output[i];
		}
		return out;
	}

	/**
	 * AES加密
	 * @param input
	 * @return
	 */
	public static byte[] AESencrypt(byte[] input){
		byte[] output = new byte[getLength(input.length)];
		AESencrypt(input, output, getLength(input.length), getSurplus(input.length));
		return output;
	}
	
	/**
	 * GZIP压缩
	 * @param input
	 * @return
	 */
	public static byte[] compress(byte[] input){
		int len = input.length;
		byte[] output = new byte[len * 2];
		for (int i = 0; i < output.length; i++) {
			output[i] = 0;
		}
		
		int num = compress(input, output, len, len * 2);
		
		byte[] out = new byte[num];
		for (int i = 0; i < num; i++) {
			out[i] = output[i];
		}
		
		return out;
	}
	
	/**
	 * GZIP解压
	 * @param input
	 * @return
	 */
	public static byte[] uncompress(byte[] input){
		int len = input.length;
		byte[] output = new byte[len * 100];
		
		int num = uncompress(input, output, len, output.length);
		
		byte[] out = new byte[num];
		for (int i = 0; i < num; i++) {
			out[i] = output[i];
		}
		
		return out;
	}
	
	/**
	 * AES解密
	 * @param input
	 * @param output
	 * @param len
	 * @return
	 */
	private static native int DecodeAESEncrypt(byte[] input, byte[] output, int len);

	/**
	 * AES加密
	 * @param input
	 * @param output
	 * @param len
	 * @param surplus
	 * @return
	 */
	private static native void AESencrypt(byte[] input, byte[] output, int len, int surplus);
	
	/**
	 * GZIP压缩
	 * @param input
	 * @param output
	 * @param len
	 * @return
	 */
	private static native int compress(byte[] input, byte[] output, int len, int predict);

	/**
	 * GZIP解压
	 * @param input
	 * @param output
	 * @param len
	 * @param predict
	 * @return
	 */
	private static native int uncompress(byte[] input, byte[] output, int len, int predict);
	
	/**
	 * 计算加密后的数组长度
	 * @param size
	 * @return
	 */
	private static int getLength(int size){
		return size + 32 - size % 16;
	}

	/**
	 * 计算分块加密需要补足的长度
	 * @param size
	 * @return
	 */
	private static int getSurplus(int size){
		return 16 - size % 16;
	}
	
	static {
		System.loadLibrary("android_safe");
	}
}
